<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
		<title>${initParam.WxAppName}</title>
		<link href="${pageContext.request.contextPath}/bettery/css/map.css" rel="stylesheet" />
		<script type="text/javascript" src="${pageContext.request.contextPath}/dewei/js/jquery.js"></script>
		<script type="text/javascript" src="${pageContext.request.contextPath}/bettery/js/jquery.validate.min.js"></script>
		<script language="javascript" src="http://webapi.amap.com/maps?v=1.2&key=e4e68a5cf6df32793a5c7f00e7d17253"></script>
		<script type="text/javascript" src="${pageContext.request.contextPath}/bettery/js/bettery_common.js"></script>
		<script type="text/javascript" src="${pageContext.request.contextPath}/bettery/js/template.js"></script>
	</head>
	<body>
	<div id="preloader"></div>
	<form id='searchForm' method="post">
		<input type="hidden" value="${model.lat}" name='model.lat' id="hiddenLat" />
		<input type="hidden" value="${model.lng}" name='model.lng' id="hiddenLng" />
		<input type="hidden" value="${model.blat}" name='model.blat' id="hiddenbLat" />
		<input type="hidden" value="${model.blng}" name='model.blng' id="hiddenbLng" />
		<input type="hidden" id="tsss">
	</form>
	<div class="search_bar" style="" align="center">
		<span class='new-btn left'><a id="backBtn" onclick="backOrCloseWindow();">关闭</a> </span> 附近活动商家
		<span class="new-btn  right"><a id="changeView" onclick="javascript:changeViewType();">地图</a> </span>
	</div>
	
	<div id='layer' class="mapContent" style='height: 100%; background: #fff; margin-top: 0px; padding-bottom: 0px; top: 45px; position: absolute;' align="center">
		<div class="container" id="span_without_map">
			<div style="margin-top:100px;font-size:14px;">正在建设中...</div>
		</div>
	</div>
	<div id="map" style='height: 100%; background: #fff; margin-top: 0px; padding-bottom: 0px; top: 45px; position: absolute;'></div>
	<div id='daohangInfo' class="footor_bar" style=''>
		<a href="#" style="float: right; top: 0px; text-decoration: none;" onclick='javascript:$("#daohangInfo").hide();'>点击关闭</a>  
		<div id="result" style='height: 135px; color: #000; bottom: 0px;'></div>
	</div>
	
	<div id='detailHtml' class="_wrappage"  style='display:none;'>
	</div>
<script type="text/javascript">
var json;
var level = 13;
//0list,1map,3detail
var isList=0;
var findMarkflag = true;
var map1;
var _lat;
var _lng;
var point;
var point2;
var points = new Array();
var infowindows = new Array();
var route_text, steps;
var polyline, extra_line1, extra_line2;
var infowindowFocus;
$(function()
{
	_lat = $("#hiddenbLat").val();
	_lng = $("#hiddenbLng").val();
	if (_lat && _lng)
	{
	queryMendianList();
	}
	else
	{
	$('.loading').css('display', 'inline-block');
	navigator.geolocation.getCurrentPosition(function(position)
	{
		_lat = position.coords.latitude;
		_lng = position.coords.longitude;
		$("#hiddenLng").val(_lng);
		$("#hiddenLat").val(_lat);
		getConvertLatLng(_lat, _lng);
	}, function(error)
	{
		$('#preloader').hide();
		switch (error.code)
		{
			case error.TIMEOUT :
				//alert("获取位置超时！您可通过点击消息界面【左下角键盘按钮】，打开【+】按钮，点击【位置】按钮，手动发送您当前位置");
			$("#layer").show();
			$("#map").hide();
			$("#span_without_map").html("获取位置超时！您可通过点击消息界面【左下角键盘按钮】，打开【+】按钮，点击【位置】按钮，手动发送您当前位置!");
			break;
		case error.PERMISSION_DENIED :
			$("#layer").show();
			$("#map").hide();
			$("#span_without_map").html("您拒绝了使用位置共享服务，查询已取消!");
			break;
		case error.POSITION_UNAVAILABLE :
			$("#layer").show();
			$("#map").hide();
			$("#span_without_map").html("获取位置超时！您可通过点击消息界面【左下角键盘按钮】，打开【+】按钮，点击【位置】按钮，手动发送您当前位置!");
			break;
	}
},
{
	maximumAge : 10000,
	timeout : 10000,
	enableHighAccuracy : true
}   );
	}
	hideLoading();	
});

//纠正位置，并载入地图
function getConvertLatLng(lat, lng)
{
	$.getJSON("../gpsparse.jsp",
	{
		lat : lat,
		lng : lng
	}, function(data)
	{
		if (data.error == 0)
		{
		$("#hiddenbLng").val(data.lng);
		$("#hiddenbLat").val(data.lat);
		_lat = $("#hiddenbLat").val();
		_lng = $("#hiddenbLng").val();
		queryMendianList();
		}
		else
		{
		$('#preloader').hide();
		$("#layer").show();
		$("#map").hide();
		$("#span_without_map").html("获取位置信息失败!");
		}
	});
}


function queryMendianList(){
	var html ="<div style='margin-top:100px;font-size:14px;'>正在建设中...</div>";
	if(json&&json.length > 0){
		html = "<div><ul>";
		for ( var i = 0; i < json.length; i = i + 1) {
			var timage='${pageContext.request.contextPath}/bettery/img/category.jpg?v=2';
			var bg='i-bg-red';
			if(json[i].imageUrl){timage=json[i].imageUrl;}
			  html+="<li style='background:#fff;'>";
			  html+="<div class='list-item' style='padding-top:5px;'><div class='p'><img onclick=\"showBigImg('"+timage+"')\" src='"+timage+"' style='height:110px;width:110px;'></div>";
			  html+="<div class='d'>";
			  html+="<div class='title' style='padding-bottom:5px;margin-top: 5px;font-size: 14px;color:#454545'><b>"+json[i].name+"</b></div>";
			  html+="<div style='padding-bottom:2px;font-size: 12px;color:#797979'>"+json[i].lxrTel+"<span class='right' style='border: 1px solid #ccc;border-radius: 4px; margin: 0px 10px;text-align: center;width: 35px'><a style='text-decoration:none;'  href='tel:"+json[i].lxrTel+"'>呼叫</a></span></div>";
			  html+="<div  style='font-size: 12px;color:#797979'>"+json[i].address+"</div>";
			  html+="<span class='new-btn-blue' ><a style='text-align:center;margin:0px;border:0;padding-left:0px;' onclick='javascript:showDetail("+json[i].id+");'>活动详情</a></span></div>";
			  html+="</div><img src='${pageContext.request.contextPath}/bettery/icons/bottom_1.png' style='margin:0;padding:0;display:block;height:1px;' width='100%'/></li>";
		}
		html+="</ul></div>";
		
		hideLoading();
	    $('#span_without_map').html(html);
	}else{
		$.ajax({
			url : "getMakers.do?lat=" + _lat + "&lng=" + _lng + "&t=" + (new Date()),
			dataType : "json",
			async : true,
			success : function(data)
			{
				if (data.success&&data.result.length>0)
				{
				   json = data.result;
				   html = "<div><ul>";
					for ( var i = 0; i < json.length; i = i + 1) {
						var timage='${pageContext.request.contextPath}/bettery/img/category.jpg?v=2';
						var bg='i-bg-red';
						if(json[i].imageUrl){timage=json[i].imageUrl;}
						  html+="<li style='background:#fff;'>";
						  html+="<div class='list-item' style='padding-top:5px;'><div class='p'><img onclick=\"showBigImg('"+timage+"')\" src='"+timage+"' style='height:110px;width:110px;'></div>";
						  html+="<div class='d'>";
						  html+="<div class='title' style='padding-bottom:5px;margin-top: 5px;font-size: 14px;color:#454545'><b>"+json[i].name+"</b></div>";
						  html+="<div style='padding-bottom:2px;font-size: 12px;color:#797979'>"+json[i].lxrTel+"<span class='right' style='border: 1px solid #ccc;border-radius: 4px; margin: 0px 10px;text-align: center;width: 35px'><a style='text-decoration:none;'  href='tel:"+json[i].lxrTel+"'>呼叫</a></span></div>";
						  html+="<div  style='font-size: 12px;color:#797979'>"+json[i].address+"</div>";
						  html+="<span class='new-btn-blue' ><a style='text-align:center;margin:0px;border:0;padding-left:0px;' onclick='javascript:showDetail("+json[i].id+");'>活动详情</a></span></div>";
						  html+="</div><img src='${pageContext.request.contextPath}/bettery/icons/bottom_1.png' style='margin:0;padding:0;display:block;height:1px;' width='100%'/></li>";
					}
					html+="</ul></div>";
					
					//此时地图也开始初始化
					//initMap();
				}
				hideLoading();
	            $('#span_without_map').html(html);
			}
		});
	}
	$("#layer").show();
	$("#map").hide();
	$("#detailHtml").hide();
}

/***gaode map**/
function loadMap()
{
	if(map1){
		$("#layer").hide();
	    $("#map").show();
	    $("#detailHtml").hide();
	}
	else if (_lat && _lng) {
		initMap();
		//根据经纬度获取客户地址
		//getaddressByLatLngGaode();
		$("#layer").hide();
		$("#map").show();
	    $("#detailHtml").hide();
	}
	else
	{
	     $("#span_without_map").html("加载地图失败!");
	}
}
//初始化地图
function initMap(){
		if(!level){level=15;}
		//高德地图
		map1 = new AMap.Map("map",{center:new AMap.LngLat(_lng, _lat),level:level});	// 创建Map实例
		AMap.event.addListener(map1,"click",function(e){if(infowindowFocus){infowindowFocus.close();$("#daohangInfo").hide();}});
		//在地图中添加ToolBar插件
		map1.plugin(["AMap.ToolBar"],function(){
			toolBar = new AMap.ToolBar();
			map1.addControl(toolBar);
		});
		point=new AMap.LngLat($("#hiddenbLng").val(),$("#hiddenbLat").val());
		
		var sicon = new AMap.Icon({
	        image: "${pageContext.request.contextPath}/bettery/img/poi.png",
	        size:new AMap.Size(44,44),
	        imageOffset: new AMap.Pixel(-334, -180)
	    });
	    var marker = new AMap.Marker({
	        icon : sicon, //复杂图标
	        visible : true,
	        position:point,
	        map:map1,
	        offset : {
	            x : -16,
	            y : -40
	        }
	    });
		marker.setMap(map1);
		addMarker();
}

function addMarker(){
	/*if(json&&json.length>0){
		for ( var i = 0; i < json.length; i = i + 1)
		{
			var html = "";
			var img = "../bettery/img/huiyuan.jpg";
			if (json[i].imageUrl)
			{
			img = json[i].imageUrl;
			}
			html += "<div>";
			html += "<div style='font-size:14px;'><b>" + json[i].name + "</b></div>";
			html += "<div><table style='font-size:12px;border:0px;text-align:left;'>";
			html += "<tr><td style='vertical-align: top;width:60px;'>地&nbsp;&nbsp;址：</td><td>" + json[i].address + "</td></tr>";
			html += "<tr><td >大约距离：</td><td>" + json[i].distance + "</td></tr>";
			html += "<tr><td colspan='2'><span class='new-btn-blue' ><a style='text-align:center;margin:0px;border:0;padding-left:0px;' onclick='javascript:daohang(" + i+ ");'>导航</a></span><span class='new-btn-blue' ><a style='text-align:center;margin:0px;border:0;padding-left:0px;' onclick='javascript:showDetail("+json[i].id+");'>活动详情</a></span></td></tr>";
			html += "</table></div>";
			html += "</div>";
			points[i]=new AMap.LngLat(json[i].longitude,json[i].latitude);
			var marker=new AMap.Marker({
			icon:new AMap.Icon({    //复杂图标
					size:new AMap.Size(28,37),//图标大小
					image:"${pageContext.request.contextPath}/bettery/img/custom_a_j.png?v=1", //大图地址
					imageOffset:new AMap.Pixel(-28*i,0)//相对于大图的取图位置
				}),
			position:points[i]
			});
			marker.setMap(map1);  //在地图上添加点

			infowindows[i] = new AMap.InfoWindow({content:html,size:new AMap.Size(250,130)}); 
			addEvent(marker,json[i].longitude,json[i].latitude, infowindows[i],map1,json[i].address,json[i].id,i,json[i].name,json[i].lxr,json[i].lxrTel);
			/*if (json[i].tuijian) {
				infowindows[i].open(map1,new AMap.LngLat(json[i].longitude,json[i].latitude));
				map1.panTo(new AMap.LngLat(json[i].longitude,json[i].latitude));  
				infowindowFocus=infowindows[i];
			}*/
		/*}
	}else{
		*/
		$.ajax({
			url : "getMakers.do?lat=" + _lat + "&lng=" + _lng,
			dataType : "json",
			async : true,
			success : function(data)
			{
				if (data.success)
				{
				if (data.result.length < 1)
				{
				$("#layer").show();
				$("#map").hide();
				}
				else
				{
					findMarkflag = true;
					json = data.result;
					findMarkflag = true;
					if(json){
						for ( var i = 0; i < json.length; i = i + 1) {
							var html = "";
							var img = "../bettery/img/huiyuan.jpg";
							if (json[i].imageUrl)
							{
							img = json[i].imageUrl;
							}
							html += "<div>";
							html += "<div style='font-size:14px;'><b>" + json[i].name + "</b></div>";
							html += "<div><table style='font-size:12px;border:0px;text-align:left;'>";
							html += "<tr><td style='vertical-align: top;width:60px;'>地&nbsp;&nbsp;址：</td><td>" + json[i].address + "</td></tr>";
							html += "<tr><td >大约距离：</td><td>" + json[i].distance + "</td></tr>";
							html += "<tr><td colspan='2'><span class='new-btn-blue' ><a style='text-align:center;margin:0px;border:0;padding-left:0px;' onclick='javascript:daohang(" + i+ ");'>导航</a></span><span class='new-btn-blue' ><a style='text-align:center;margin:0px;border:0;padding-left:0px;' onclick='javascript:showDetail("+json[i].id+");'>活动详情</a></span></td></tr>";
							html += "</table></div>";
							html += "</div>";
							points[i]=new AMap.LngLat(json[i].longitude,json[i].latitude);
							var marker=new AMap.Marker({
							icon:new AMap.Icon({    //复杂图标
									size:new AMap.Size(28,37),//图标大小
									image:"${pageContext.request.contextPath}/bettery/img/custom_a_j.png?v=1", //大图地址
									imageOffset:new AMap.Pixel(-28*i,0)//相对于大图的取图位置
								}),
							position:points[i]
							});
							marker.setMap(map1);  //在地图上添加点
							
							infowindows[i] = new AMap.InfoWindow({content:html,size:new AMap.Size(250,130)}); 
							if (json[i].tuijian) {
								infowindows[i].open(map1,new AMap.LngLat(json[i].longitude,json[i].latitude));
								map1.panTo(new AMap.LngLat(json[i].longitude,json[i].latitude));  
								infowindowFocus=infowindows[i];
							}
							addEvent(marker,json[i].longitude,json[i].latitude, infowindows[i],map1,json[i].address,json[i].id,i,json[i].name,json[i].lxr,json[i].lxrTel);
						}
					}
				}
				}
				else
				{
				$('#preloader').hide();
				$("#span_without_map").hide();
				$("#layer").show();
				$("#map").hide();
				$("#detailHtml").hide();
				}
			}
		});	
	/*}*/
}

function addEvent(marker,longitude,latitude, infowindow,map1,address,id,i,name,lxr,lxrTel){
	AMap.event.addListener(marker,"click",function(){  
		infowindow.open(map1,new AMap.LngLat(longitude,latitude));
		point2=new AMap.LngLat(longitude,latitude);
		map1.panTo(point2);  
		infowindowFocus=infowindows[i];
	}); 
}

function backOrCloseWindow(){
	switch(isList)
	{
		case 0:
			closeWindow();
			break;
		case 1:
			isList=0;
			queryMendianList();
			 $("#backBtn").html("关闭");
			$("#daohangInfo").hide();
			$("#changeView").html("地图");
		  break;
		case 2:
		    isList=0;
		    $("#backBtn").html("关闭");
			queryMendianList();
			$("#daohangInfo").hide();
			$("#changeView").html("地图");
		  break;
		default:
			isList=0;
		    $("#backBtn").html("关闭");
			queryMendianList();
			$("#changeView").html("地图");
	}
}


function changeViewType(){
	$("#backBtn").html("返回");
	/**0list,1map,3detail**/
	switch(isList)
	{
		case 0:
			isList=1;
			loadMap();
			$("#changeView").html("列表");
			
			break;
		case 1:
			isList=0;
			queryMendianList();
			$("#daohangInfo").hide();
			$("#backBtn").html("关闭");
			$("#changeView").html("地图");
		  break;
		case 2:
			closeWindow();
		  break;
		default:
			isList=0;
			queryMendianList();
			$("#changeView").html("地图");
	}
}

function daohang(i){
	$("#daohangInfo").show();
	point2=points[i];
	var MWalk;map1.plugin(["AMap.Walking"], function() {MWalk = new AMap.Walking();AMap.event.addListener(MWalk, "complete", driving_routeCallBack);MWalk.search(point, point2);});
}
//导航结果展示
function driving_routeCallBack(data) {
	if(null!=polyline){
		polyline.hide( );
	}
	if(null!=extra_line1){
	extra_line1.hide( );
	}
	if(null!=extra_line2){
	extra_line2.hide( );
	}
   var routeS = data.routes;
    if (null==routeS||routeS.length <= 0) {
	document.getElementById("result").innerHTML = "未查找到任何结果";
    }
    else{
	     route_text="";
        for(var v =0; v< routeS.length;v++){
            //驾车步骤数
            steps = routeS[v].steps;
            var route_count = steps.length;
            //行车距离（米）
            var distance = routeS[v].distance;
            //拼接输出html
            for(var i=0 ;i< steps.length;i++){
                route_text +=  "&nbsp;"+(1+i) +"." +steps[i].instruction  + "<br/>";
            }
        }        
        document.getElementById("result").innerHTML = route_text;
        drivingDrawLine();
    }  
}
//绘制驾车导航路线
function drivingDrawLine(s) {
    //起点到路线的起点 路线的终点到终点 绘制无道路部分
    var extra_path1 = new Array();
    extra_path1.push(point);
    extra_path1.push(steps[0].path[0]);
    extra_line1 = new AMap.Polyline({
        map: map1,
        path: extra_path1,
        strokeColor: "#9400D3",
        strokeOpacity: 0.7,
        strokeWeight: 4,
        strokeStyle: "dashed",
        strokeDasharray: [10, 5]
    });
 
    var extra_path2 = new Array();
    var path_xy = steps[(steps.length-1)].path;
    extra_path2.push(point2);
    extra_path2.push(path_xy[(path_xy.length-1)]);
    extra_line2 = new AMap.Polyline({
        map: map1,
        path: extra_path2,
        strokeColor: "#9400D3",
        strokeOpacity: 0.7,
        strokeWeight: 4,
        strokeStyle: "dashed",
        strokeDasharray: [10, 5]
    });
     
    var drawpath = new Array();
    for(var s=0; s<steps.length; s++) {
        var plength = steps[s].path.length;
        for (var p=0; p<plength; p++) {
            drawpath.push(steps[s].path[p]);
        }
    }
    polyline = new AMap.Polyline({
        map: map1,
        path: drawpath,
        strokeColor: "#9400D3",
        strokeOpacity: 0.7,
        strokeWeight: 4,
        strokeDasharray: [10, 5]
    });

if(infowindowFocus){infowindowFocus.close();}
//map1.setFitView();
map1.panTo(point); 
}
function showBigImg(img){
        $("<div id='bigImg' style='width:100%;margin-top:45px;'><img style='width:100%' onclick=\"showListImg();\"  src='" + img+ "'/></div>").appendTo("body");
        $("#span_without_map").hide();
        $("#bigImg").show();$("#layer").css("background-image","");$("#mendianList").hide();
        $("body").css("background-color","#333");
        var height=document.documentElement.clientHeight-45;

        var imgWidth = $("#bigImg").find("img").width();

       $("#bigImg").css("line-height",height*1.8-80+"px");
        $("#bigImg").css("height",height+"px");

        $("#bigImg").css("text-align","center");
        var winWidth = document.documentElement.clientWidth;

        $("#bigImg").find("img").css("max-width",winWidth+"px");
    }
function showListImg(){
	$("#bigImg").remove();
	$("#span_without_map").show();
}


function showDetail(id)
{
    var d;
	//先考虑在本页显示
	if(json){
		for ( var i = 0; i < json.length; i = i + 1) {
		    var j=json[i];
			if(j.id==id){
			    d=j;
				break;
			}
		}
	}
	if(d){
		$("#layer").show();
		$("#map").hide();
		if(!map1){
			initMap();
		}
		
		var html = template('detailTpl', d);
		document.getElementById('detailHtml').innerHTML = html;
		
		isList=2;
		$("#changeView").html("关闭");
		$("#backBtn").html("返回");
		$("#detailHtml").show();
		$("#layer").hide();
	    $("#map").hide();
	}else{
	     location.href="queryDetail.do?id="+id+"&t="+(new Date());
	}
}
function showPoint(id){
	if(json){
		loadMap();
		for ( var i = 0; i < json.length; i = i + 1) {
			if(json[i].id==id){
			
				isList=1;
		        $("#changeView").html("列表");
				
			    infowindows[i].open(map1,new AMap.LngLat(json[i].longitude,json[i].latitude));
				map1.panTo(new AMap.LngLat(json[i].longitude,json[i].latitude));  
				infowindowFocus=infowindows[i];
			}
		}
	}
}
</script>
		
		
<script id="detailTpl" type="text/html">
 <div class="inf_head">
{{if imageUrl}} <img src="{{imageUrl}}" onerror="javascript:this.src='${pageContext.request.contextPath}/bettery/img/logo2.jpg'"     class="p-pic"> 
{{/if}}
{{if !imageUrl}}<img src="${pageContext.request.contextPath}/bettery/img/logo2.jpg"  class="p-pic">{{/if}}
			
	        <p>{{name}}</p>
	    </div>
	    <div class="informations">
	        <strong>商家信息</strong>    <span class="right" style="margin:0px; text-align:center;"><img src='../dewei/img/loc.png' width='14px'>{{distance}}</span><br/>
	        商家名称：<span>{{name}}</span>   <span style="border: 1px solid #ccc;border-radius: 4px; margin: 0px 0px;text-align:center;width: 45px;color:#f00;" class="right"><a onclick="showPoint({{id}});" style="text-decoration:none;">地图</a></span> <br/>
	        商家地址：<span>{{address}}</span>
	    </div>
	    <div class="informations">
	        <strong>活动详情</strong><br/>
	        活动时间：<span>{{actiBeginTime}} 至 {{actiEndTime}}</span>
	        <p>
	        {{detailInfo}}
	        </p>
	    </div>
	    <div class="informations">
	        <strong>活动须知</strong><br/>
	        使用时间：<span>{{allowTime}}</span><br/>
	        使用规则：<span>{{useRules}}</span><br/>
	        不可用日期：<span>{{invaliDates}}</span><br/>
	   </div>
</script>
	</body>
</html>